/*
 * @Author: yangzonglong
 * @Date: 2021-05-07 13:25:11
 * @version: v1.0.0
 * @Descripttion: 表单模板
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-08-11 10:02:05
 * @Auditor: 
 */
import React, { useMemo, useCallback, useRef, useState, useEffect } from 'react';
import { PageHeader, Table, Search, Button, history, ActionText, units } from '@library';
import { TableRefProps } from '@library/components/table/interface';
import { Select } from 'antd';
import { ColumnsSetButton, useSetColumnsFun } from '../../components/customColumns/CustomColumnsButton';
import QueryProps from '@library/interface/apiQuery';
import { FormProps } from './../../interface';
import { removeForm } from './api';
import i18n from "@library/app/i18n";

import QuerySession from '../../components/querySession/_QuerySession';
const QuerySessionIns = new QuerySession();

const t = window.$app.t;

const columns = [
  { dataIndex: 'formName', title: t('formName'), width: 300, tooltip: true, ellipsis: true },
  { dataIndex: 'formDesc', title: t('formDesc'), width: 300, tooltip: true, ellipsis: true },
  { dataIndex: 'formEngine', title: t('formEngine'), width: 120, tooltip: true, ellipsis: true },
  { dataIndex: 'functionCode', title: t('functionCode'), width: 120, tooltip: true, ellipsis: true },
  { dataIndex: 'functionGroupDesc', title: t('functionGroup'), width: 120, tooltip: true, ellipsis: true },
  { dataIndex: 'functionOrder', title: t('functionOrder'), width: 120, tooltip: true, ellipsis: true },
  { dataIndex: 'updatedAt', title: t('updatedAt'), format: 'time', width: 150, tooltip: true, ellipsis: true },
  { dataIndex: 'action', title: t('action'), width: 80, tooltip: true, ellipsis: true, fixed: 'right' }
];

const toCrate = () => history.push('/form/details');
const where = { categoryCode: undefined };

export default () => {
  const tableRef = useRef<TableRefProps>(null);
  const searchRef = useRef<any>(null);
  const [query, setQuery] = useState<QueryProps>({ where });
  const [moduleCode, setModuleCode] = useState('all');
  const [modules, setModules] = useState<{ moduleName: string; moduleCode: string; moduleEnName: string; }[]>([]);

  //  columns原始值(useModel过来的)  columnsNeeds中间值(如下定义即可) columnsList最终值(table展示用的)
  const [columnsNeeds, setColumnsNeeds] = useState<typeof columns>([]);
  const columnsList = useSetColumnsFun?.(columnsNeeds);

  useEffect(() => {
    units.serverLoading('/bk/api/console/ServiceModule/find', {}).then(res => {
      setModules([{ moduleName: t('all'), moduleCode: 'all', moduleEnName: 'All' }].concat(res.rows));
    });
  }, []);

  useEffect(() => {
    if (history._isFromBreadcrumb) {
      const queryObj = QuerySessionIns.getQuerySession();
      if (queryObj) {
        setQuery(queryObj || { where });
        setModuleCode(queryObj?.where?.categoryCode || 'all');
        searchRef.current?.setValue(queryObj.fuzzyValue);
      }
      history._isFromBreadcrumb = false;
    }
  }, []);

  const onRemove = useCallback(async (id: string) => {
    const result = await removeForm(id);
    if (result) {
      units.message.success();
      tableRef.current?.onRefresh();
    }
  }, []);

  const onSearch = useCallback((fuzzyValue: string) => {
    setQuery({
      fuzzyQuery: true,
      fuzzyValue,
      fuzzyField: ['formName', 'formDesc'],
      where: { categoryCode: moduleCode === 'all' ? undefined : moduleCode }
    });
  }, [moduleCode]);

  const extra = useMemo(() => [
    {
      dataIndex: 'action', render(text: string, record: FormProps) {
        return (
          <>
            <ActionText.Edit type='detail' onClick={() => {
              const query = tableRef.current?.getQuery!();
              QuerySessionIns.setQuerySession(query);
              history.push('/form/details?id=' + record.id);
            }} />
            <ActionText.Delete onClick={() => onRemove(record.id!)} isModalTip />
          </>
        );
      }
    }
  ], [onRemove]);

  function onChangeModule(e: string) {
    setModuleCode(e);

    setQuery({
      where: { categoryCode: e === 'all' ? undefined : e }
    });
  }

  function onDoubleClick({ id }: { id: string; }) {
    const query = tableRef.current?.getQuery!();
    QuerySessionIns.setQuerySession(query);
    history.push('/form/details?id=' + id);
  }

  return (
    <>
      <PageHeader />
      <div className='common-block-table'>
        <PageHeader extra={
          <>
            <Select
              value={moduleCode}
              onChange={onChangeModule}
              style={{ width: '120px' }}>
              {modules.map(item => (
                <Select.Option key={item.moduleCode}>
                  {i18n.language === 'en' ? item.moduleEnName : item.moduleName}
                </Select.Option>
              ))}
            </Select>
            <span className='wingBlank' />
            <Search onSearch={onSearch} placeholder={window.$app.t('searchFormListTip')} ref={searchRef} />
            <Button.Create onClick={toCrate} />
            <ColumnsSetButton columns={columns} onSendColumns={setColumnsNeeds} businessId="workflow.form" />
          </>
        } />
        <Table
          ref={tableRef}
          query={query}
          extra={extra}
          columns={columnsList}
          onDoubleClick={onDoubleClick}
          recordSort='FormList'
          url='/bk/api/fd/Form/find' />
      </div>
    </>
  );
};